package com.ruoyi.zsyh.controller.applet.store;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 服务订单 -- 全部订单
 */
@Controller
@RequestMapping("/applet/zsyh/personOrderRepair")
public class ZsyhPersonOrderRepairAppletController extends BaseController
{

    @Autowired
    private IZsyhServiceOrderService zsyhServiceOrderService;

    @Autowired
    private IZsyhUserRepairstoreService zsyhUserRepairstoreService;

    @Autowired
    private IZsyhUserRepairareaService zsyhUserRepairareaService;

    @Autowired
    private IZsyhServiceOrderPartsService zsyhServiceOrderPartsService;

    @Autowired
    private IZsyhServiceOrderPartsRelService zsyhServiceOrderPartsRelService;

    @Autowired
    private IZsyhServiceOrderMessageService zsyhServiceOrderMessageService;

    @Autowired
    private IZsyhServiceOrderApplymoneyService zsyhServiceOrderApplymoneyService;

    @Autowired
    private IZsyhServiceOrderAppointmentService zsyhServiceOrderAppointmentService;

    @Autowired
    private IZsyhServiceOrderLogService zsyhServiceOrderLogService;

    @Autowired
    private IZsyhServiceOrderSettlementService zsyhServiceOrderSettlementService;

    @Autowired
    private IZsyhAfterCommissionSettingService zsyhAfterCommissionSettingService;

    @Autowired
    private IZsyhPersonOrderMoneyService zsyhPersonOrderMoneyService;

    @Autowired
    private IZsyhPersonOrderService zsyhPersonOrderService;

    /**
     * 维修师傅 订单中心 各个订单状态列表
     * @param orderState 0新工单 1待预约 101待上门 102服务中 2已完成
     * 订单状态 0未接单 1已接单 101已预约 102服务中 2已完成 3已支付 4已评价 5已取消 6系统自动取消
     * @return
     */
    @RequestMapping("/getPersonOrderList")
    @ResponseBody
    public AjaxResult getPersonOrderList(String userId, String orderState, String pageNum, String pageSize, String key)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();//师傅的店铺id

        //orderState 订单状态 0未接单 1已接单 101已预约 102服务中 2已完成 3已支付 4已评价 5已取消 6系统自动取消
        Map map = new HashedMap();
        ZsyhPersonOrder order = new ZsyhPersonOrder();
        order.setOrderState(orderState);

        if(!"0".equals(orderState)){
            order.setRepairStoreId(repairId);
        }else{
            ZsyhUserRepairarea area = new ZsyhUserRepairarea();
            area.setRepairId(repairId);
            List<ZsyhUserRepairarea> areaList = zsyhUserRepairareaService.selectZsyhUserRepairareaList(area);
            String areaIds = "";
            for(ZsyhUserRepairarea a:areaList){
                areaIds += a.getRepairDistrict() + ",";
            }
            map.put("areaIds", areaIds);
        }

        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        map.put("key", key);
        order.setParams(map);
        List<ZsyhPersonOrder> orderList = zsyhPersonOrderService.selectZsyhPersonOrderList(order);//首页订单列表

        return success("成功", orderList);
    }


    /**
     * 维修师傅 订单中心 订单详情
     * @return
     */
    @RequestMapping("/getPersonOrderDetails")
    @ResponseBody
    public AjaxResult getPersonOrderDetails(String userId, String orderId)throws Exception
    {
        //主订单
        ZsyhPersonOrder order = zsyhPersonOrderService.selectZsyhPersonOrderById(orderId);
        return success("成功", order);
    }

    /**
     * 接单  维修师傅接单
     * @return
     * @throws Exception
     */
    @RequestMapping("/receivePersonOrder")
    @ResponseBody
    public AjaxResult receivePersonOrder(String orderId, String userId)throws Exception
    {
        ZsyhPersonOrder order1 = zsyhPersonOrderService.selectZsyhPersonOrderById(orderId);
        String orderUserId = order1.getUserId();
        if(userId.equals(orderUserId)){
            return error("请勿接自己下的订单");
        }

        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();

        ZsyhPersonOrder order = new ZsyhPersonOrder();
        order.setId(orderId);
        order.setRepairStoreId(repairId);
        //订单状态 0未接单 1已接单 101已预约 102服务中 2已完成 3已支付 4已评价 5已取消 6系统自动取消
        order.setOrderState("1");
        order.setReceiptTime(new Date());
        zsyhPersonOrderService.updateZsyhPersonOrderApplet(order);

        return success("成功");
    }

    /**
     * 维修师傅 订单中心 预约客户
     * @return
     */
    @RepeatSubmit
    @Transactional
    @RequestMapping("/appointmentPersonOrder")
    @ResponseBody
    public AjaxResult appointmentPersonOrder(String userId, String orderId, String appointmentDate, String appointmentContent)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();//师傅的店铺id

        ZsyhServiceOrderAppointment appointment = new ZsyhServiceOrderAppointment();
        appointment.setId(IdWorker.getId());
        appointment.setOrderId(orderId);
        appointment.setRepairId(repairId);
        appointment.setAppointmentDate(appointmentDate);
        appointment.setAppointmentContent(appointmentContent);
        zsyhServiceOrderAppointmentService.insertZsyhServiceOrderAppointment(appointment);

        ZsyhPersonOrder order = new ZsyhPersonOrder();
        order.setId(orderId);
        order.setOrderState("101");
        order.setAppointmentTime(new Date());
        zsyhPersonOrderService.updateZsyhPersonOrderApplet(order);

        return success("成功");
    }

    /**
     * 维修师傅 订单中心 取消订单申请
     * @return
     * @throws Exception
     */
    @RequestMapping("/cancelPersonOrder")
    @ResponseBody
    public AjaxResult cancelPersonOrder(String orderId, String userId, String cancelRemark)throws Exception
    {
        ZsyhPersonOrder order = new ZsyhPersonOrder();
        order.setId(orderId);
        order.setOrderState("5");
        zsyhPersonOrderService.updateZsyhPersonOrderApplet(order);

        return success("成功");
    }

    /**
     * 维修师傅 订单中心 确认上门
     * @return
     * @throws Exception
     */
    @RequestMapping("/confirmPersonOrder")
    @ResponseBody
    public AjaxResult confirmPersonOrder(String orderId, String userId)throws Exception
    {
        ZsyhPersonOrder order = new ZsyhPersonOrder();
        order.setId(orderId);
        order.setOrderState("102");
        order.setTodoorTime(new Date());
        zsyhPersonOrderService.updateZsyhPersonOrderApplet(order);

        return success("成功");
    }

    /**
     * 完成服务
     * @param orderId
     * @param userId
     * @return
     * @throws Exception
     */
    @RepeatSubmit
    @Transactional
    @RequestMapping("/finishPersonOrder")
    @ResponseBody
    public AjaxResult finishPersonOrder(String orderId, String userId, String orderImage, String orderRemarks, String moneyJson, String orderServiceMoney)throws Exception
    {
        ZsyhPersonOrder _order = zsyhPersonOrderService.selectZsyhPersonOrderById(orderId);
        String orderType = _order.getOrderType();//订单分类 1个人订单 2扫码订单
        String rakerId = _order.getRakerId();

        List<Map<String, Object>> list = JSON.parseObject(moneyJson, new TypeReference<List<Map<String, Object>>>() {});
        Date date = new Date();
        for(Map<String, Object> a:list){
            String typeMoneyId = String.valueOf(a.get("typeMoneyId"));
            String typeMoneyName = String.valueOf(a.get("typeMoneyName"));
            String money = String.valueOf(a.get("money"));
            String moneyType = String.valueOf(a.get("moneyType"));

            ZsyhPersonOrderMoney orderMoney =new ZsyhPersonOrderMoney();
            orderMoney.setId(IdWorker.getId());
            orderMoney.setCreateTime(date);
            orderMoney.setTypeMoneyId(typeMoneyId);
            orderMoney.setTypeMoneyName(typeMoneyName);
            orderMoney.setMoney(new BigDecimal(money));
            orderMoney.setOrderId(orderId);
            orderMoney.setTypeMoneyId(moneyType);
            zsyhPersonOrderMoneyService.insertZsyhPersonOrderMoney(orderMoney);
        }

        ZsyhPersonOrder order = new ZsyhPersonOrder();
        order.setId(orderId);
        order.setOrderState("2");
        order.setCompleteImage(orderImage);
        order.setCompleteRemark(orderRemarks);
        order.setCompleteTime(new Date());
        order.setOrderServiceMoney(new BigDecimal(orderServiceMoney));
        if("2".equals(_order.getOrderType())){
            ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreById(rakerId);
            String rakerCommission = store.getRakerCommission();//贴码订单 提成比例 百分比
            double _rakerCommission = 0.0;
            try {
                _rakerCommission = Double.valueOf(rakerCommission);
            }catch (Exception e){

            }
            BigDecimal orderFixdraw = new BigDecimal(orderServiceMoney).multiply(new BigDecimal(_rakerCommission)).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            order.setOrderFixdraw(orderFixdraw);
        }


        zsyhPersonOrderService.updateZsyhPersonOrderApplet(order);


        return success("成功");
    }

    /**
     * 维修师傅 个人中心 个人单 待结算 已结算
     * orderFixdrawState 固定抽成费用支付状态 0未支付 1已支付
     *  0待结算 1已结算
     * @return
     */
    @RequestMapping("/getPersonOrderListBYRepairId")
    @ResponseBody
    public AjaxResult getPersonOrderListBYRepairId(String userId, String orderFixdrawState, String pageNum, String pageSize)throws Exception
    {
        ZsyhUserRepairstore store = zsyhUserRepairstoreService.selectZsyhUserRepairstoreByUserId(userId);
        String repairId = store.getId();//师傅的店铺id

        //orderState 订单状态 0未接单 1已接单 101已预约 102服务中 2已完成 3已支付 4已评价 5已取消 6系统自动取消
        Map map = new HashedMap();
        ZsyhPersonOrder order = new ZsyhPersonOrder();

        order.setRepairStoreId(repairId);
        order.setOrderFixdrawState(orderFixdrawState);

        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }

        map.put("orderState", "已完成");
        order.setParams(map);
        List<ZsyhPersonOrder> orderList = zsyhPersonOrderService.selectZsyhPersonOrderList(order);//首页订单列表

        return success("成功", orderList);
    }


}
